package com.github.catvod.utils;

import com.github.catvod.crawler.SpiderDebug;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author fus
 * 开发请求接口
 */
public class FusRequests {
    public static String environment_Dev="dev";
    public static String environment_Local="dev";
    private static int Prod=33210;
    private static String Address="127.0.0.1";

    /**
     *
     * @param url
     * @param header
     * @param position 开发环境代理还是线上环境代理
     * @return
     */
    public static String requestProxy(String url, HashMap<String, String> header,String position){
        try {
            Proxy proxy;
            // 开发环境代理还是线上环境代理
            if (position.equals(environment_Dev)){
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Address, Prod));
            }else {
                // 获取系统环境代理，后续 使用代理
                proxy = new OkHttpClient().proxy();
            }
            OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
            Request.Builder build = new Request.Builder().url(url);
            // 进行设置请求头
            for (String key : header.keySet()) {
                build.addHeader(key, Objects.requireNonNull(header.get(key)));
            }
            Request req = build.build();
            Response response = client.newCall(req).execute();
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}
